import 'dart:async';

import 'package:flutter/scheduler.dart';
import 'package:get/get.dart';
import 'xh_danmu_models.dart';

import 'xh_danmu_debug.dart';
import 'xh_danmu_stream.dart';

/// XH弹幕控制器
class XhDanmuController extends GetxController with GetSingleTickerProviderStateMixin {
  late Ticker _ticker;
  late XhDanmuConfig _config;
  bool _isInitialized = false;

  // 轨道列表
  final List<XhDanmuTrack> _tracks = [];

  // 所有活跃弹幕（用于渲染）
  final RxList<XhDanmuItem> activeDanmuList = <XhDanmuItem>[].obs;

  // 容器尺寸
  double _containerWidth = 0.0;
  double _containerHeight = 0.0;

  // 动画状态
  bool _isPlaying = false;
  double _currentTime = 0.0;
  double _pausedTime = 0.0;

  // 弹幕ID计数器
  int _danmuIdCounter = 0;

  // 性能统计
  int _totalDanmuSent = 0;
  int _totalDanmuCompleted = 0;

  // 更新控制 - 减少闪烁
  double _lastUpdateTime = 0.0;
  static const double _updateInterval = 1.0 / 25.0; // 25FPS更新频率，平衡流畅度和性能

  // 智能更新控制
  bool _hasVisualChanges = false;
  int _consecutiveNoChangeFrames = 0;
  static const int _maxNoChangeFrames = 10; // 连续10帧无变化后才降低更新频率

  // Stream订阅管理
  StreamSubscription<XhDanmuData>? _streamSubscription;

  @override
  void onInit() {
    super.onInit();
    _ticker = createTicker(_onTick);
    XhDanmuDebug.infoPrint('XH弹幕控制器初始化完成');
  }

  /// 初始化弹幕系统
  void initialize(XhDanmuConfig config) {
    if (_isInitialized) return;

    _config = config;
    _initializeTracks();
    _isInitialized = true;

    XhDanmuDebug.infoPrint('XH弹幕系统配置完成: ${_config.trackCount}轨道, ${_config.minSpacing}px间距');
  }

  /// 初始化轨道
  void _initializeTracks() {
    _tracks.clear();
    _updateTracksLayout();
  }

  /// 更新轨道布局（根据容器高度）
  void _updateTracksLayout() {
    if (_containerHeight <= 0) return;

    final dynamicTrackHeight = _config.calculateDynamicTrackHeight(_containerHeight);

    _tracks.clear();
    for (int i = 0; i < _config.trackCount; i++) {
      _tracks.add(XhDanmuTrack(
        trackId: i,
        topOffset: _config.getDynamicTrackTopOffset(i, _containerHeight),
        height: dynamicTrackHeight,
        minSpacing: _config.minSpacing,
      ));
    }

    XhDanmuDebug.debugPrint('轨道布局更新: ${_config.trackCount}条轨道, 高度${dynamicTrackHeight.toStringAsFixed(1)}px');
  }

  /// 动画帧回调
  void _onTick(Duration elapsed) {
    if (!_isPlaying) return;

    final elapsedSeconds = elapsed.inMicroseconds / 1000000.0;
    _currentTime = _pausedTime + elapsedSeconds;

    // 控制更新频率，避免过于频繁的UI更新
    bool needsUpdate = false;

    // 处理等待队列
    final queueProcessed = _processWaitingQueues();
    if (queueProcessed) needsUpdate = true;

    // 更新弹幕位置
    final positionsChanged = _updateDanmuPositions();
    if (positionsChanged) needsUpdate = true;

    // 清理完成的弹幕
    final cleaned = _cleanupCompletedDanmu();
    if (cleaned) needsUpdate = true;

    // 智能更新策略：减少闪烁
    if (needsUpdate) {
      _hasVisualChanges = true;
      _consecutiveNoChangeFrames = 0;
    } else {
      _consecutiveNoChangeFrames++;
    }

    // 动态调整更新频率
    final adaptiveInterval = _consecutiveNoChangeFrames > _maxNoChangeFrames
        ? _updateInterval * 1.5 // 无变化时轻微降低频率
        : _updateInterval;

    // 如果有活跃弹幕，即使没有明显变化也要定期更新确保流畅度
    final hasActiveDanmu = activeDanmuList.isNotEmpty;
    final shouldUpdate =
        _hasVisualChanges || (hasActiveDanmu && (_currentTime - _lastUpdateTime) >= adaptiveInterval);

    if (shouldUpdate) {
      _lastUpdateTime = _currentTime;
      _hasVisualChanges = false;
      update(['danmu_layer']); // 只更新弹幕层，减少重绘范围
    }
  }

  /// 发送弹幕组件
  ///
  /// [component] 弹幕组件
  /// [speed] 弹幕移动速度，如果为null则使用配置中的默认速度
  void sendDanmuComponent(
    XhDanmuComponent component, {
    double? speed,
  }) {
    // 确保容器已初始化
    if (_containerWidth <= 0) {
      XhDanmuDebug.warnPrint('容器宽度未设置，弹幕将在容器初始化后发送');
      return;
    }

    _totalDanmuSent++;

    // 创建弹幕项
    final danmu = XhDanmuItem(
      id: 'xh_danmu_${++_danmuIdCounter}',
      component: component,
      speed: speed ?? _config.speed,
      trackId: -1, // 临时值，稍后分配
      startTime: _currentTime,
    );

    XhDanmuDebug.debugPrint(
        '发送弹幕: "${component.id}" (${danmu.logicalWidth.toStringAsFixed(1)}px x ${_config.trackHeight.toStringAsFixed(1)}px)');

    // 智能轨道分配
    final selectedTrack = _selectOptimalTrack(danmu);
    danmu.trackId = selectedTrack.trackId;

    // 检查是否可以立即添加
    if (selectedTrack.canAddDanmu(_containerWidth, _currentTime, danmu.logicalWidth)) {
      _activateDanmu(danmu, selectedTrack);
      XhDanmuDebug.debugPrint('弹幕直接添加到轨道${selectedTrack.trackId}');
    } else {
      selectedTrack.waitingQueue.add(danmu);
      XhDanmuDebug.debugPrint('弹幕加入轨道${selectedTrack.trackId}等待队列');
    }

    // 确保动画运行
    if (!_isPlaying) {
      startAnimation();
    }

    // 立即更新UI
    update(['danmu_layer']);
  }

  /// 智能选择最优轨道
  XhDanmuTrack _selectOptimalTrack(XhDanmuItem danmu) {
    // 首先尝试找到可以立即添加的轨道
    final availableTracks = _tracks
        .where((track) => track.canAddDanmu(_containerWidth, _currentTime, danmu.logicalWidth))
        .toList();

    if (availableTracks.isNotEmpty) {
      // 在可用轨道中选择负载最低的
      availableTracks.sort((a, b) => a.loadScore.compareTo(b.loadScore));
      return availableTracks.first;
    }

    // 如果没有可用轨道，选择负载最低的轨道
    _tracks.sort((a, b) => a.loadScore.compareTo(b.loadScore));
    return _tracks.first;
  }

  /// 激活弹幕
  void _activateDanmu(XhDanmuItem danmu, XhDanmuTrack track) {
    danmu.isActive = true;
    danmu.startTime = _currentTime;
    danmu.currentX = _containerWidth;
    danmu.calculateEndTime(_containerWidth);

    track.activeDanmuList.add(danmu);
    activeDanmuList.add(danmu);

    XhDanmuDebug.debugPrint('弹幕激活: "${danmu.component.id}" 轨道${track.trackId}');
  }

  /// 处理等待队列
  bool _processWaitingQueues() {
    bool processed = false;

    for (final track in _tracks) {
      if (track.waitingQueue.isNotEmpty) {
        final danmu = track.waitingQueue.first;

        if (track.canAddDanmu(_containerWidth, _currentTime, danmu.logicalWidth)) {
          track.waitingQueue.removeAt(0);
          _activateDanmu(danmu, track);
          processed = true;

          XhDanmuDebug.debugPrint('队列弹幕激活: "${danmu.component.id}" 轨道${track.trackId}');
        }
      }
    }

    return processed;
  }

  /// 更新弹幕位置
  bool _updateDanmuPositions() {
    if (_containerWidth <= 0) return false;

    bool positionsChanged = false;

    for (final danmu in activeDanmuList) {
      if (danmu.isActive && !danmu.isCompleted) {
        final oldX = danmu.currentX;
        final newX = danmu.calculatePosition(_containerWidth, _currentTime);

        // 只有位置真正改变时才更新
        if (oldX == null || (oldX - newX).abs() > 0.1) {
          danmu.currentX = newX;
          positionsChanged = true;
        }

        // 检查是否完全离开屏幕
        if (danmu.isCompletelyOffScreen(_containerWidth) && !danmu.isCompleted) {
          danmu.isCompleted = true;
          _totalDanmuCompleted++;
          positionsChanged = true;

          XhDanmuDebug.debugPrint(
              '弹幕完成: "${danmu.component.id}" 生存${(_currentTime - danmu.startTime).toStringAsFixed(1)}s');
        }
      }
    }

    return positionsChanged;
  }

  /// 清理已完成的弹幕
  bool _cleanupCompletedDanmu() {
    final beforeCount = activeDanmuList.length;
    final danmuToRemove = <XhDanmuItem>[];

    // 只清理已标记为完成的弹幕
    for (final danmu in activeDanmuList) {
      if (danmu.isCompleted) {
        danmuToRemove.add(danmu);
      }
    }

    // 移除已完成的弹幕
    for (final danmu in danmuToRemove) {
      activeDanmuList.remove(danmu);

      // 从对应轨道中移除
      try {
        final track = _tracks.firstWhere((t) => t.trackId == danmu.trackId);
        track.activeDanmuList.remove(danmu);
      } catch (e) {
        XhDanmuDebug.warnPrint('找不到轨道${danmu.trackId}');
      }
    }

    final removedCount = beforeCount - activeDanmuList.length;

    if (removedCount > 0) {
      XhDanmuDebug.debugPrint('清理弹幕${removedCount}条，剩余${activeDanmuList.length}条');
    }

    return removedCount > 0;
  }

  /// 更新容器尺寸
  void updateContainerSize(double width, double height) {
    final widthChanged = width != _containerWidth;
    final heightChanged = height != _containerHeight;

    if (widthChanged || heightChanged) {
      XhDanmuDebug.debugPrint(
          '容器尺寸更新: ${_containerWidth.toStringAsFixed(1)}x$_containerHeight -> ${width.toStringAsFixed(1)}x$height');

      _containerWidth = width;
      _containerHeight = height;

      // 如果高度发生变化，需要重新计算轨道布局
      if (heightChanged && _isInitialized) {
        _updateTracksLayout();
      }

      // 如果宽度发生变化，需要重新计算所有弹幕的结束时间
      if (widthChanged) {
        for (final danmu in activeDanmuList) {
          danmu.calculateEndTime(_containerWidth);
        }
      }
    }
  }

  /// 开始动画
  void startAnimation() {
    if (!_isPlaying) {
      _isPlaying = true;
      // 确保Ticker处于正确状态
      if (_ticker.isActive) {
        _ticker.stop();
      }
      _ticker.start();
      XhDanmuDebug.infoPrint('动画开始');
      update(['danmu_layer']); // 立即更新UI状态
    }
  }

  /// 暂停动画
  void pauseAnimation() {
    if (_isPlaying) {
      _isPlaying = false;
      _pausedTime = _currentTime;
      if (_ticker.isActive) {
        _ticker.stop();
      }
      XhDanmuDebug.infoPrint('动画暂停');
      update(['danmu_layer']); // 立即更新UI状态
    }
  }

  /// 停止动画并重置
  void stopAnimation() {
    if (_ticker.isActive) {
      _ticker.stop();
    }
    _isPlaying = false;
    _currentTime = 0.0;
    _pausedTime = 0.0;
    XhDanmuDebug.infoPrint('动画停止');
    update(['danmu_layer']); // 立即更新UI状态
  }

  /// 清空所有弹幕
  void clearAllDanmu() {
    activeDanmuList.clear();
    for (final track in _tracks) {
      track.clear();
    }

    stopAnimation();
    _danmuIdCounter = 0;
    _totalDanmuSent = 0;
    _totalDanmuCompleted = 0;

    update(['danmu_layer']);
    XhDanmuDebug.infoPrint('所有弹幕已清空');
  }

  /// 获取弹幕系统状态
  XhDanmuStatus getStatus() {
    final trackInfos = _tracks
        .map((track) => XhDanmuTrackInfo(
              trackId: track.trackId,
              activeDanmuCount: track.activeDanmuList.length,
              queuedDanmuCount: track.waitingQueue.length,
              status: track.status,
              loadScore: track.loadScore,
            ))
        .toList();

    return XhDanmuStatus(
      isPlaying: _isPlaying,
      currentTime: _currentTime,
      containerWidth: _containerWidth,
      totalActiveDanmu: activeDanmuList.length,
      totalQueuedDanmu: _tracks.fold(0, (sum, track) => sum + track.waitingQueue.length),
      trackInfos: trackInfos,
    );
  }

  /// 批量发送弹幕组件
  void sendBatchDanmuComponent(List<XhDanmuComponent> components) {
    for (final component in components) {
      sendDanmuComponent(component);
    }
  }

  /// 连接弹幕数据流
  void connectStream(Stream<XhDanmuData> stream) {
    // 先断开之前的连接
    disconnectStream();

    _streamSubscription = stream.listen(
      (danmuData) {
        // 直接发送组件
        sendDanmuComponent(danmuData.component);
      },
      onError: (error) {
        XhDanmuDebug.errorPrint('弹幕流错误: $error');
      },
    );

    XhDanmuDebug.infoPrint('弹幕数据流已连接');
  }

  /// 断开弹幕数据流
  void disconnectStream() {
    _streamSubscription?.cancel();
    _streamSubscription = null;
    XhDanmuDebug.infoPrint('弹幕数据流已断开');
  }

  /// 连接弹幕数据源
  void connectDataSource(XhDanmuDataSource dataSource) {
    connectStream(dataSource.stream);
  }

  /// 启用调试模式
  void enableDebugMode() {
    XhDanmuDebug.setDebugMode(true);
  }

  /// 禁用调试模式
  void disableDebugMode() {
    XhDanmuDebug.setDebugMode(false);
  }

  /// 调试：打印详细状态
  void debugPrintStatus() {
    if (!XhDanmuDebug.debugMode) {
      XhDanmuDebug.setDebugMode(true);
    }

    for (final track in _tracks) {
      XhDanmuDebug.debugPrint(
          '轨道${track.trackId}: ${track.status.name} (负载${track.loadScore.toStringAsFixed(1)})');
      XhDanmuDebug.debugPrint('  活跃: ${track.activeDanmuList.length}条, 队列: ${track.waitingQueue.length}条');

      // 显示前2个活跃弹幕的详细信息
      final activeDanmus = track.activeDanmuList.take(2);
      for (final danmu in activeDanmus) {
        final x = danmu.currentX ?? _containerWidth;
        final rightEdge = x + danmu.logicalWidth;
        final isVisible = danmu.isVisible(_containerWidth);
        XhDanmuDebug.debugPrint(
            '    "${danmu.component.id}": x=${x.toStringAsFixed(1)}, 右边缘=${rightEdge.toStringAsFixed(1)}, 可见=$isVisible');
      }
    }
    XhDanmuDebug.debugPrint('===== 状态结束 =====');
  }

  // Getters
  bool get isPlaying => _isPlaying;
  double get currentTime => _currentTime;
  double get containerWidth => _containerWidth;
  double get containerHeight => _containerHeight;
  XhDanmuConfig get config => _config;
  List<XhDanmuTrack> get tracks => List.unmodifiable(_tracks);
  int get totalDanmuSent => _totalDanmuSent;
  int get totalDanmuCompleted => _totalDanmuCompleted;

  @override
  void onClose() {
    // 断开Stream连接
    disconnectStream();

    if (_ticker.isActive) {
      _ticker.stop();
    }
    _ticker.dispose();
    super.onClose();
    XhDanmuDebug.infoPrint('XH弹幕控制器已销毁');
  }
}
